package com.pl.dailycollection.study.lock;

import jdk.internal.org.objectweb.asm.tree.TryCatchBlockNode;

import javax.lang.model.element.VariableElement;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName SynchronizedTest
 * @Description: 通过lock实现库存增减
 * @Author pl
 * @Date 2019/12/31
 * @Version V1.0
 **/
public class InventoryByLock {
    //库存量
    private int count=0;
    //最大促存量
    private int MAX_COUNT= 10;
    //锁
    private ReentrantLock lock = new ReentrantLock();
    //不为空
    private Condition notEmpty = lock.newCondition();
    //不满
    private Condition notFull = lock.newCondition();

    public void add(){
        lock.lock();
        try {
            while (count>=MAX_COUNT)
                notFull.await();
            count++;
            notEmpty.notifyAll();
        }catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void remove(){
        lock.lock();
        try {
            while (count<=0)
                notEmpty.await();
            count--;
            notFull.notifyAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
